﻿using BLL.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FlowerShopMVC.Controllers
{
    public class CartController : Controller
    {
        private readonly CartService _cartService;

        public CartController()
        {
            _cartService = new CartService();
        }

        // 显示购物车内容
        public ActionResult Index()
        {
            // 获取当前用户ID（假设从Session中获取）
            int userId = Convert.ToInt32(Session["UserId"]);
            var cartItems = _cartService.GetCartItems(userId);

            // 计算总价和利润
            var totals = _cartService.CalculateCartTotals(userId);
            ViewBag.TotalPrice = totals.totalPrice;
            //ViewBag.TotalProfit = totals.totalProfit;

            return View(cartItems);
        }

        // 添加商品到购物车
        [HttpPost]
        public ActionResult AddToCart(int productId)
        {
            // 获取当前用户ID
            int userId = Convert.ToInt32(Session["UserId"]);
            _cartService.AddToCart(userId, productId);

            return RedirectToAction("Index");
        }

        // 从购物车中删除商品
        [HttpPost]
        public ActionResult RemoveFromCart(int productId)
        {
            // 获取当前用户ID
            int userId = Convert.ToInt32(Session["UserId"]);
            _cartService.RemoveFromCart(userId, productId);

            return RedirectToAction("Index");
        }

        // 清空购物车
        public ActionResult ClearCart()
        {
            // 获取当前用户ID
            int userId = Convert.ToInt32(Session["UserId"]);
            _cartService.ClearCart(userId);

            return RedirectToAction("Index");
        }

        // 提交订单
        [HttpPost]
        public ActionResult SubmitOrder()
        {
            // 获取当前用户ID
            int userId = Convert.ToInt32(Session["UserId"]);
            var cartItems = _cartService.GetCartItems(userId);

            if (!cartItems.Any())
            {
                TempData["Message"] = "购物车为空，请添加商品后再提交订单！";
                return RedirectToAction("Index");
            }

            // 这里可以添加订单提交的逻辑，例如保存订单到数据库
            // 例如：_orderService.CreateOrder(userId, cartItems);

            // 清空购物车
            _cartService.ClearCart(userId);

            TempData["Message"] = "订单提交成功！";
            return RedirectToAction("Index");
        }
    }
}